#include <unordered_map>
using namespace std;
/*
 * @lc app=leetcode.cn id=146 lang=cpp
 *
 * [146] LRU 缓存
 */

// @lc code=start
struct Node {
    int key, val;
    Node *pre, *next;
    Node(int i, int j, Node *p, Node *n): key(i), val(j), pre(p), next(n) { }
    Node(): Node(0, 0, nullptr, nullptr) {}
    Node(int i, int j): Node(i, j, nullptr, nullptr) {}
};

class LRUCache {
public:
    Node *head, *tail;
    unordered_map<int, Node*> mapper;
    int sz, cp;
    LRUCache(int capacity): sz(0), cp(capacity) {
        head = new Node(); tail = new Node();
        head->pre = nullptr; head->next = tail;
        tail->pre = head; tail->next = nullptr;
    }
    
    int get(int key) {
        if (!mapper.count(key)) return -1;
        Node *target = mapper[key];
        remove_node(target);
        add_head(target);
        return target->val;
    }

    void put(int key, int value) {
        if (!mapper.count(key)) {
            if (sz < cp) {
                Node *target = new Node(key, value);
                add_head(target);
                mapper.insert({key, target});
                sz++;
            } else {
                Node *t = tail->pre;
                mapper.erase(t->key);
                mapper.insert({key, t});
                t->key = key; t->val = value;
                remove_node(t); add_head(t);
            }
        }
        else {
            Node *target = mapper[key];
            target->val = value;
            remove_node(target);
            add_head(target);
        }
    }

    void remove_node(Node *node) {
        node->pre->next = node->next;
        node->next->pre = node->pre;
    } 

    void add_head(Node *node) {
        head->next->pre = node;
        node->next = head->next;
        head->next = node;
        node->pre = head;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
// @lc code=end

